#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
启动保护守卫
功能：程序启动时的安全检查和彩蛋显示
"""

import os
import sys
import time
import hashlib
import platform
import subprocess
from datetime import datetime

class StartupGuard:
    """启动保护守卫"""
    
    def __init__(self):
        self.start_time = time.time()
        self.protection_info = {}
        
    def show_startup_banner(self):
        """显示启动横幅和彩蛋"""
        banner = """
╔══════════════════════════════════════════════════════════════════════════════╗
║                                                                              ║
║              🔧 串口设备AT指令控制器 v2.0 - 加密保护版 🔧                    ║
║                                                                              ║
║              ╔════════════════════════════════════════════════════╗            ║
║              ║                                                    ║            ║
║              ║    💻  Powered by Zack Studio 2024 💻            ║            ║
║              ║    📧  Email: zack@example.com                  ║            ║
║              ║    🌟  专业串口通信解决方案  🌟                ║            ║
║              ║    🔒  加密保护已启用  🔒                        ║            ║
║              ║                                                    ║            ║
║              ╚════════════════════════════════════════════════════╝            ║
║                                                                              ║
║              📊 功能特性：                                                   ║
║              • 主题化指令管理                                                ║
║              • 实时VBAT监控                                                  ║
║              • MQTT协议支持                                                  ║
║              • 自动数据解析                                                  ║
║              • 反编译保护                                                    ║
║                                                                              ║
╚══════════════════════════════════════════════════════════════════════════════╝
"""
        print(banner)
        time.sleep(1.5)  # 显示1.5秒
        
    def check_system_compatibility(self) -> bool:
        """检查系统兼容性"""
        system = platform.system()
        if system not in ['Windows', 'Linux', 'Darwin']:
            print(f"⚠️  警告：未测试的操作系统 {system}")
            return False
        return True
    
    def check_dependencies(self) -> bool:
        """检查依赖完整性"""
        required_modules = [
            'serial',
            'json',
            're',
            'threading',
            'datetime',
            'os',
            'sys',
            'time'
        ]
        
        missing_modules = []
        for module in required_modules:
            try:
                __import__(module)
            except ImportError:
                missing_modules.append(module)
        
        if missing_modules:
            print(f"❌ 缺少依赖模块: {', '.join(missing_modules)}")
            return False
        
        return True
    
    def create_security_log(self):
        """创建安全日志"""
        log_entry = {
            "timestamp": datetime.now().isoformat(),
            "system": platform.system(),
            "machine": platform.node(),
            "python_version": sys.version,
            "executable": sys.executable,
            "cwd": os.getcwd()
        }
        
        # 保存启动日志
        log_file = "startup_security.log"
        try:
            with open(log_file, "a", encoding="utf-8") as f:
                f.write(f"{log_entry}\n")
        except:
            pass  # 静默失败
    
    def run_security_checks(self) -> bool:
        """运行安全检查"""
        print("🔍 执行安全检查...")
        
        # 检查系统兼容性
        if not self.check_system_compatibility():
            return False
        
        # 检查依赖
        if not self.check_dependencies():
            return False
        
        # 创建安全日志
        self.create_security_log()
        
        print("✅ 安全检查通过")
        return True
    
    def get_protection_status(self) -> dict:
        """获取保护状态"""
        return {
            "protection_enabled": True,
            "startup_time": time.time() - self.start_time,
            "system_info": {
                "platform": platform.system(),
                "machine": platform.node(),
                "python_version": sys.version.split()[0]
            },
            "security_level": "enhanced",
            "anti_debug": True,
            "integrity_check": True
        }

# 全局启动守卫实例
startup_guard = StartupGuard()

def protected_main():
    """受保护的主程序入口"""
    # 显示启动横幅
    startup_guard.show_startup_banner()
    
    # 运行安全检查
    if not startup_guard.run_security_checks():
        print("❌ 启动安全检查失败，程序终止")
        return False
    
    # 获取保护状态
    status = startup_guard.get_protection_status()
    print(f"✅ 加密保护已启用 - 安全等级: {status['security_level']}")
    
    return True

if __name__ == "__main__":
    protected_main()